package org.firecloud.h5fun.controller;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonFunction;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.ColumnBean;
import org.json.JSONObject;
/**
 * Web setup listener
 * @author fc
 *
 */
public class MainServletContextListener extends HttpServlet implements ServletContextListener {

	private static final long serialVersionUID = 1L;
	
	/**
	 * Web setup listener destroyed function now is empty
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		
	}
	
	/**
	 * Web setup listener init function do:
	 * 1.Parse json for WEB-INF/config to init config
	 * 2.Select columns set to application
	 */
	public void contextInitialized(ServletContextEvent sce) {
		Connection connection = null;
    	try {
    		BasicConfigurator.configure();
    		String configfilepath = sce.getServletContext().getRealPath("WEB-INF")+"/config.json";
    		String config_json_src = CommonFunction.file_read_string(configfilepath);
    		CommonConfig config = new CommonConfig(new JSONObject(config_json_src));
    		sce.getServletContext().setAttribute("commonConfig",config);
			connection = config.getConn();
			List<ColumnBean> columns = new ArrayList<ColumnBean>();
			CommonQuery.select_columns(connection,columns);
			sce.getServletContext().setAttribute("columns", columns);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().equals(e);
				}
			}
		}
	}
}
